import pylibdmtx.pylibdmtx as dmtx
import sys
import copy
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageEnhance

def genImage(text):
    dmcode = dmtx.encode(text.encode('utf8'))
    width, height = int(dmcode.width * 4.5), int(dmcode.height * 1.1)
    dmcode_pos = (int(dmcode.width * 0), int(dmcode.height * 0.05))
    label = Image.new('RGB', (width, height), (255, 255, 255))
    label.paste(Image.frombytes('RGB', (dmcode.width, dmcode.height), dmcode.pixels), dmcode_pos)

    str_pos = (int(dmcode.width * 1.1), int(dmcode.height * 0.00))
    draw = ImageDraw.Draw(label)
    #font = ImageFont.truetype('FreeMonoBold.ttf', 60)
    #font = ImageFont.truetype('FreeSans.ttf', 50)
    #font = ImageFont.truetype('samanata.ttf', 50)
    font = ImageFont.truetype('kalimati.ttf', 50)
    draw.text(str_pos, text, font=font, fill=(0, 0, 0))

    label.save('barcode.jpg')

    label = label.filter(ImageFilter.GaussianBlur(radius=2))
    #label = label.filter(ImageFilter.BLUR)

    enh_sha = ImageEnhance.Sharpness(label)
    en = enh_sha.enhance(5)
    en.show()

    en.save('barcode_.jpg')

if __name__=='__main__':
    if len(sys.argv) > 1:
        genImage(sys.argv[1])
    else:
        while True:
            txt = input('input:')
            if txt == 'q':
                break
            genImage(txt)
